package com.example.user.manger;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.redis.service.RedisService;
import com.example.user.domain.teacher.Teacher;
import com.example.user.domain.teacher.vo.TeacherDetailVO;
import com.example.user.mapper.teacher.TeacherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class TeacherCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private TeacherMapper teacherMapper;

    /* 用户个人中心功能,查看个人详情 */
    public TeacherDetailVO getTeacherById(Long teacherId) {
        String teacherKey = getTeacherKey(teacherId);
        TeacherDetailVO teacherDetailVO = redisService.getCacheObject(teacherKey, TeacherDetailVO.class);
        if (teacherDetailVO != null) {
            //将缓存延长10min
            redisService.expire(teacherKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return teacherDetailVO;
        }
        Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>()
                .select(Teacher::getTeacherId,
                        Teacher::getTitle,
                        Teacher::getNickName,
                        Teacher::getHeadImage,
                        Teacher::getEmail,
                        Teacher::getPhone,
                        Teacher::getHireDate,
                        Teacher::getBirthday,
                        Teacher::getAddress,
                        Teacher::getSex,
                        Teacher::getIdentificationCard,
                        Teacher::getBio)
                .eq(Teacher::getTeacherId, teacherId));
        if (teacher == null) {
            return null;
        }
        refreshTeacher(teacher);
        teacherDetailVO = new TeacherDetailVO();
        BeanUtil.copyProperties(teacher, teacherDetailVO);
        return teacherDetailVO;
    }

    public void refreshTeacher(Teacher teacher) {
        //刷新用户缓存
        String teacherKey = getTeacherKey(teacher.getTeacherId());
        redisService.setCacheObject(teacherKey, teacher);
        //设置用户缓存有效期为10分钟
        redisService.expire(teacherKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }

    //u:d:用户id
    private String getTeacherKey(Long teacherId) {
        return CacheConstants.TEACHER_DETAIL + teacherId;
    }
}
